package es.us.lsi.daw.dao.impl;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import es.us.lsi.daw.model.security.Group;
import es.us.lsi.daw.model.security.enums.GroupEnum;
import es.us.lsi.daw.dao.DAOAuthorization;

@Component
@Transactional
//TODO(mamuso) Should this reside in ModelSecurity?
public class DAOAuthorizationImpl extends DAOComunImpl implements DAOAuthorization {

//	@Override
//	public Set<Group> getGroupFromEnum(Set<GroupEnum> setGroupEnum) {
//		//IMPROVE(mamuso) make this criteria more efficient
//		Session session = this.sessionFactory.openSession();
//		Set<Group> result = new HashSet<Group>();
//		for (GroupEnum ge: setGroupEnum) {
//			Group g = (Group) session
//					.createCriteria(Group.class)
//					.add(Restrictions.eq(Group.A_GROUP, ge.name()))
//					.uniqueResult();
//			if (g != null) {
//				result.add(g);
//			}
//		}
//		return result;
//	}
	
	public Group getGroupFromString(String name) {
		//This is kind of a hack to get an instance
		GroupEnum ge = GroupEnum.getFromString(name);
		Session session = this.sessionFactory.openSession();
		Group result = (Group) session
					.createCriteria(Group.class)
					.add(Restrictions.eq(Group.A_GROUP, ge))
					.uniqueResult();
		return result;
	}
	

//	@Override
//	public Set<Authority> getAuthorityFromEnum(Set<AuthorityEnum> setAuthorityEnum) {
//		//IMPROVE(mamuso) make this criteria more efficient
//				Session session = this.sessionFactory.openSession();
//				Set<Authority> result = new HashSet<Authority>();
//				for (AuthorityEnum ge: setAuthorityEnum) {
//					Authority g = (Authority) session
//							.createCriteria(Authority.class)
//							.add(Restrictions.eq(Authority.A_AUTHORITY, ge.name()))
//							.uniqueResult();
//					if (g != null) {
//						result.add(g);
//					}
//				}
//				return result;
//	}

	public Group[] getAllGroups() {
		Session session = this.sessionFactory.openSession();
		@SuppressWarnings("unchecked")
		List<Group> lstGroups = (List<Group>) session
				.createCriteria(Group.class)
				.list();
		Group[] arrGroups = new Group[lstGroups.size()];
		return lstGroups.toArray(arrGroups);
	}

	
	
	
}
